//
//  LoginViewController.swift
//  Runner
//
//  Created by Bingo on 2025/8/26.
//
import UIKit
import TXLoginoauthSDK
import WebKit

class LoginViewController :UIViewController,UAFSDKLoginDelegate{
    
    var checkedP = false
    
    //运营商： 移动：mobile； 联通：unicom；电信：telecom
    var carrier : Int = 0
    
    var uiModel = TXLoginUIModel()
    
    // 其他属性...
    private var contentView: UIView!
    private var titleLabel: UILabel!
    private var actionButton: UIButton!
    private var closeButton: UIButton!
    private var textField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    func authViewPrivacyCheckboxStateToggled(_ checked: Bool) {
        print("checked = \(checked)")
        checkedP = checked
    }
    
    func authRequestWillStart(_ loginEvent: @escaping UAFContinueLoginEvent) {
        print("authRequestWillStart")
        
        if (checkedP) {
            loginEvent(true);
            return;
        }
        
        // 找到最顶层 VC（兼容 FlutterViewController）
        if let topVC = topViewController() {
            // 如果调用时机太早，授权页还没消失，延迟一点
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
            
                // 在视图控制器中显示弹窗
                CarrierAgreementView.show(
                    in: topVC.view,
                    onConfirm: {
                        print("用户同意了协议")
                        // 执行运营商认证逻辑
                        loginEvent(true)

                    },
                    onCancel: {
                        print("用户取消了协议确认")
                        // 处理取消逻辑
                        loginEvent(false)
                    },
                    onLinkTap: { linkType in
                        switch linkType {
                        case .userAgreement:
                            print("点击了用户服务协议")
                            // 打开用户服务协议页面
                            let webVc = WebViewController(url: "https://static.ichibankuji.cn/html/user_protocol.html")
                            let navVC = UINavigationController(rootViewController: webVc)
                            topVC.present(navVC, animated: true)
                        case .privacyPolicy:
                            print("点击了隐私政策")
                            let webVc = WebViewController(url: "https://static.ichibankuji.cn/html/privacy_policy.html")
                            let navVC = UINavigationController(rootViewController: webVc)
                            topVC.present(navVC, animated: true)
                        case .carrierAgreement:
                            self.carrierType(vc: topVC)
                
                        }
                    }
                )
                
            }
        }
    }
    
    func carrierType(vc:UIViewController)  {
        var carrierUrl = ""
        switch carrier {
        case 1:
            print("移动运营商")
            carrierUrl = "https://wap.cmpassport.com/resources/html/contract.html"
        case 2:
            print("联通运营商")
            carrierUrl = "https://auth.wosms.cn/html/oauth/protocol3.html?top=true&darkMode=true"
        case 3:
            print("电信运营商")
            carrierUrl = "https://e.189.cn/sdk/agreement/detail.do?appKey=E_189&hidetop=true&returnUrl="
           
        default:
            print("不识别的运营商")
            return
        }
 
        let webVc = WebViewController(url: carrierUrl)
        let navVC = UINavigationController(rootViewController: webVc)
        vc.present(navVC, animated: true)
    }
    
    /// 获取最顶层可见 VC
    func topViewController(
        base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController
    ) -> UIViewController? {
        
        if let nav = base as? UINavigationController {
            return topViewController(base: nav.visibleViewController)
        }
        if let tab = base as? UITabBarController {
            return topViewController(base: tab.selectedViewController)
        }
        if let presented = base?.presentedViewController {
            return topViewController(base: presented)
        }
        return base
    }
    
}

class WebViewController: UIViewController, WKNavigationDelegate {
    
    private var webView: WKWebView!
    private var loadingIndicator: UIActivityIndicatorView!
    private var urlString: String
    
    init(url: String) {
        self.urlString = url
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        setupWebView()
        setupLoadingIndicator()
        loadRequest()
    }
    
    private func setupNavigationBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(
            title: "关闭",
            style: .plain,
            target: self,
            action: #selector(closeButtonTapped)
        )
    }
    
    private func setupWebView() {
        let config = WKWebViewConfiguration()
        config.allowsInlineMediaPlayback = true
        
        webView = WKWebView(frame: view.bounds, configuration: config)
        webView.navigationDelegate = self
        webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.addSubview(webView)
    }
    
    private func setupLoadingIndicator() {
        if #available(iOS 13.0, *) {
            loadingIndicator = UIActivityIndicatorView(style: .large)
        } else {
            // Fallback on earlier versions
        }
        loadingIndicator.center = view.center
        loadingIndicator.hidesWhenStopped = true
        view.addSubview(loadingIndicator)
    }
    
    private func loadRequest() {
        guard let url = URL(string: urlString) else {
            showAlert(message: "无效的URL地址")
            return
        }
        
        loadingIndicator.startAnimating()
        webView.load(URLRequest(url: url))
    }
    
    @objc private func closeButtonTapped() {
        dismiss(animated: true)
    }
    
    // MARK: - WKNavigationDelegate
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        loadingIndicator.stopAnimating()
        title = webView.title
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        loadingIndicator.stopAnimating()
        showAlert(message: "加载失败: \(error.localizedDescription)")
    }
    
    private func showAlert(message: String) {
        let alert = UIAlertController(title: "提示", message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
}



